# -*- coding: utf-8 -*-
"""
@Time ： 2023/10/13 10:15
@Auth ： dorabmon
@File ：sdata.py
@IDE ：PyCharm
"""
# -*- coding:utf-8 -*-
"""
@File : my_mysql.py
@Time : 2022/9/3 17:32
"""
import pymysql



# 建立数据库连接
def connect_to_mysql():
    try:
        conn = pymysql.connect(
            host='localhost',
            user='root',
            password='123456',
            database='company'
        )
        return conn
    except pymysql.Error as err:
        print(f"Error: {err}")
        return None


# 执行查询语句
def execute_query(conn, query, data=None):
    cursor = conn.cursor()
    try:
        if data:
            cursor.execute(query, data)
        else:
            cursor.execute(query)
        result = cursor.fetchall()
        return result
    except pymysql.Error as err:
        print(f"Error: {err}")
        return None
    finally:
        cursor.close()


# 执行插入、更新和删除语句
def execute_insert_update_delete(conn, query, data=None):
    cursor = conn.cursor()
    try:
        if data:
            cursor.execute(query, data)
        else:
            cursor.execute(query)
        conn.commit()
    except pymysql.Error as err:
        print(f"Error: {err}")
    finally:
        cursor.close()


# 关闭数据库连接
def close_connection(conn):
    conn.close()


if __name__ == "__main__":
    connection = connect_to_mysql()

    if connection:
        # select_query = "SELECT * FROM t_employees where deptno=30;"
        select_query = "SELECT * FROM t_employees where deptno=30;"
        result = execute_query(connection, select_query)
        if result:
            for row in result:
                print(row)


